﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Cache;

namespace LevenBlog.Core.Service {
    public static class UserType {
        private static readonly string cacheName = "levenblog_servicecache_usertype";

        public static IList<lb_usertype> Get(IDbProvider provider) {
            IList<lb_usertype> find = ObjectCache.Get<IList<lb_usertype>>(cacheName);
            if (find == null) {
                find = ProviderManager.Factory.UserType.Get(provider);
                ObjectCache.Insert(cacheName, find);
            }
            return find;
        }

        public static lb_usertype Get(IDbProvider provider, int id) {
            return Get(provider).FirstOrDefault(ut => ut.id == id);
        }

        public static lb_usertype Get(IDbProvider provider, string name) {
            return Get(provider).FirstOrDefault(ut => ut.name == name);
        }

        public static lb_usertype GetDefault(IDbProvider provider) {
            return Get(provider, 1);
        }

        public static void Update(IDbProvider provder, lb_usertype usertype) {
            ProviderManager.Factory.UserType.Update(provder, usertype);
            Remove();
        }

        public static void Delete(IDbProvider provider, int id) {
            //默认用户权限id为2,id为1,2,3的用户组为系统用户组,不允许删除
            if (id == 1 || id == 2 || id == 3)
                throw new Exception("该用户组不允许删除.");
            provider.BeginTransaction();
            try {
                IList<lb_user> userList = ProviderManager.Factory.User.GetFromTypeID(provider, id);
                foreach (lb_user user in userList) {
                    user.typeid = 2;
                }
                ProviderManager.Factory.UserType.Delete(provider, id);
                provider.Commit();
            } catch (Exception e) {
                provider.Rollback();
                throw new Exception(string.Format("删除用户组{0}失败.", Get(provider, id).name), e);
            }
            Remove();
        }

        public static void Insert(IDbProvider provider, lb_usertype usertype) {
            ProviderManager.Factory.UserType.Insert(provider, usertype);
            Remove();
        }

        public static void Remove() {
            ObjectCache.Remove(cacheName);
        }
    }
}
